package com.mall.order.biz.handler;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.biz.convert.CreateOrderConvert;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.dto.OrderDto;
import com.mall.order.dto.OrderItemDto;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * ciggar
 * create-date: 2019/8/1-下午5:01
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        // 取出所需参数
        CreateOrderContext orderContext = (CreateOrderContext) context;
        String userName = orderContext.getUserName();
        Long userId = orderContext.getUserId();
//        String orderId = String.valueOf(new Date().getTime());
        String orderId = String.valueOf(UUID.randomUUID().getLeastSignificantBits()).substring(1);
        orderContext.setOrderId(orderId);

        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();

        // 插入order表
        int i = insert2Order(userName, orderId, cartProductDtoList,userId);

        // 插入order_item表
        insert2OrderItem(orderId, cartProductDtoList);

        return i == 1;
    }

    private int insert2Order(String userName, String orderId, List<CartProductDto> cartProductDtoList,Long userId) {
        // 1. 计算订单中所有商品的价格
        BigDecimal totalPrice = new BigDecimal(0);
        for (CartProductDto productDto : cartProductDtoList) {
            Long productNum = productDto.getProductNum();
            BigDecimal salePrice = productDto.getSalePrice();
            totalPrice = totalPrice.add(BigDecimal.valueOf(productNum * salePrice.intValue()));
        }
        // 插入订单
        Order order = new Order();
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setBuyerNick(userName);
        order.setStatus(0);
        order.setOrderId(orderId);
        order.setPayment(totalPrice);
        order.setUserId(userId);

        int i = orderMapper.insertSelective(order);
        return i;
    }

    private void insert2OrderItem(String orderId, List<CartProductDto> cartProductDtoList) {
        LinkedList<OrderItem> orderItems = new LinkedList<OrderItem>();
        for (CartProductDto cartProductDto : cartProductDtoList) {

            // 拿出需要的参数
            String id = String.valueOf(UUID.randomUUID().getLeastSignificantBits()).substring(1);
            int num = Math.toIntExact(cartProductDto.getProductNum());
            BigDecimal price = cartProductDto.getSalePrice();
            Long productId = cartProductDto.getProductId();
            String productImg = cartProductDto.getProductImg();
            String productName = cartProductDto.getProductName();
            // 新建一个orderItem, 填入数据
            OrderItem orderItem = new OrderItem();
            orderItem.setId(id);
            orderItem.setOrderId(orderId);
            orderItem.setNum(num);
            orderItem.setPrice(price.doubleValue());
            orderItem.setTotalFee(num * price.doubleValue());
            orderItem.setItemId(productId);
            orderItem.setPicPath(productImg);
            orderItem.setTitle(productName);
            orderItem.setStatus(1);

            // 加入到list
            orderItems.add(orderItem);
        }
        // 整个list直接添加
        orderItemMapper.insertLists(orderItems);
    }
}
